import 'dart:async';
import 'dart:io';

import 'package:flutter/services.dart';

class VertuGeneralUtils {
  // 定义与原生代码通信的通道名称
  static const MethodChannel _channel = MethodChannel(
    'com.vertu.general.channel',
  );
  static const EventChannel _eventChannel = EventChannel(
    'com.vertu.general.event',
  );

  // 事件流控制器
  static StreamController<Map<String, dynamic>>? _eventController;
  static Stream<Map<String, dynamic>>? _eventStream;

  // 获取事件流
  static Stream<Map<String, dynamic>> get eventStream {
    if (_eventStream == null) {
      _eventController = StreamController<Map<String, dynamic>>.broadcast();
      _eventStream = _eventController!.stream;

      // 设置事件通道监听
      _eventChannel.receiveBroadcastStream().listen(
        (event) {
          if (event is Map) {
            _eventController?.add(Map<String, dynamic>.from(event));
          }
        },
        onError: (error) {
          print('接收general事件错误: $error');
          _eventController?.addError(error);
        },
      );
    }
    return _eventStream!;
  }

  static Future<Map<String, String>?> getDeviceRelatedParamMap() async {
    try {
      final Map<dynamic, dynamic> result = await _channel.invokeMethod(
        'getDeviceRelatedParamMap',
      );
      var data = Map<String, String>.from(result);
      // var uid = UserController.to.currentUser.value?.id;
      // if (uid != null) data['uid'] = uid.toString();
      return data;
    } on PlatformException catch (e) {
      print('获取getDeviceRelatedParamMap失败: ${e.message}');
      return Future.value();
    }
  }

  static Future<bool> installApk(String path) async {
    if (Platform.isIOS) return Future.value(false);
    try {
      print('准备安装APK: $path');
      final bool result = await _channel.invokeMethod('installApk', {
        "path": path,
      });
      print('安装APK结果: $result');
      return result;
    } on PlatformException catch (e) {
      print('installApk-err: ${e.message}');
      throw Exception('安装APK失败: ${e.message}');
    }
  }

  /// 同步用户信息到原生
  static Future<void> syncUserToNative(String userJson) async {
    if (Platform.isIOS) return Future.value();
    try {
      await _channel.invokeMethod('saveUser', userJson);
    } catch (e) {
      print('syncUserToNative-err: $e');
    }
  }
}
